package com.yx.china.project.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PayService {
    //服务降级start
    public String paymentInfo_OK(Integer id){
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_OK,id："+id+"-->"+"O(∩_∩)O哈哈~";
    }

    @HystrixCommand(fallbackMethod = "timeOutHandler",commandProperties = {
            //设置这个线程的超时时间是5s，5s内是正常的业务逻辑，超过3s调用fallbackMethod指定的方法进行处理
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String paymentInfo_Timeout(Integer id){
        try{
            TimeUnit.SECONDS.sleep(id);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return "线程池："+Thread.currentThread().getName()+"success,id："+id+"\t"+"-->"+"   耗时(秒)："+id;
    }

    public String timeOutHandler(Integer id){
        return "线程池："+Thread.currentThread().getName()+"业务处理超时："+id+"\t"+"-->"+"   耗时(秒)："+id;
    }
    //服务降级end

    //服务熔断start
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),   //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),  //请求次数(熔断触发的最小个数/10s 默认值：20)
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),    //时间窗口期(熔断多少秒后去尝试请求，默认5s)
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),    //失败大于value时跳闸(失败率达到多少百分比后，开始短路。默认50%)
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id < 0){
            throw new RuntimeException("******id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();  //UUID.randomUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号："+serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍后再试，o(╥﹏╥)o  id："+id;
    }
    //服务熔断结束
}
